﻿using System;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class Window1Record : WorkbookLevelRecord
    {
        public Window1Record()
        {
            
        }
        private short xWn = 360;
        private short yWn = 105;
        private short dxWn = 14355;
        private short dyWn = 6210;
        private byte flag1 = 56;

        private ushort itabCur;

        private ushort itabFirst;
        private ushort ctabSel = 1;
        private ushort wTabRatio = 600;

        public Window1Record(Workbook workbook)
        {
            if (workbook.View != null)
            {
                this.ctabSel = 1;
                if (workbook.View.ActiveSheet != null)
                itabCur = (ushort) workbook.Sheets.IndexOf(workbook.View.ActiveSheet);
            }
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            xWn = context.ReadInt16();
            yWn = context.ReadInt16();
            dxWn = context.ReadInt16();
            dyWn = context.ReadInt16();
            flag1 = context.ReadByte();
            var unused = context.ReadByte();
            itabCur = context.ReadUInt16();
            itabFirst = context.ReadUInt16();
            ctabSel = context.ReadUInt16();
            wTabRatio = context.ReadUInt16();
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.Window1; }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            context.Write(xWn);
            context.Write(yWn);
            context.Write(dxWn);
            context.Write(dyWn);
            context.Write(flag1);
            context.Write((byte)0);
            context.Write(itabCur);
            context.Write(itabFirst);
            context.Write(ctabSel);
            context.Write(wTabRatio);
        }

        public override void Apply(BiffReaderWorkbookContext context)
        {
            context.GetActions(ActionType.View).Add((o) =>
                                                        {
                                                            if (context.Workbook.View == null)
                                                                context.Workbook.View = new WorkbookView(context.Workbook);
                                                            context.Workbook.View.ActiveSheet =
                                                                context.Workbook.Sheets[this.itabCur];
                                                        });
        }
    }
}